package com.sgb.kjwl.view.ui.activity.self.goods;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.PopupWindow;

import androidx.core.util.Pair;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.sgb.kjwl.BR;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityVipPriceManageBinding;
import com.sgb.kjwl.model.entity.business.StorageManEntity;
import com.sgb.kjwl.model.entity.enterprise.IpPickSelectEntity;
import com.sgb.kjwl.model.entity.self.VipPriceMangeListEntity;
import com.sgb.kjwl.utils.DialogFunction;
import com.sgb.kjwl.utils.DialogHelper;
import com.sgb.kjwl.view.event.self.VipPriceEvent;
import com.sgb.kjwl.view.ui.adapter.map.AdapterOnItemClick;
import com.sgb.kjwl.view.ui.adapter.self.goods.VipPriceManageListAdpater;
import com.sgb.kjwl.view.widget.CategoryPopWindow3;
import com.sgb.kjwl.view.widget.DictWindow3;
import com.sgb.kjwl.view.widget.IpPopWindow;
import com.sgb.kjwl.view.widget.StoragePopWindow;
import com.sgb.kjwl.viewmodel.self.goods.VipPriceManageVieModel;
import com.sgb.link.router.PathGoods;
import com.swgk.core.common.base.BaseActivity;
import com.swgk.core.dialog.BasePopWindow;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;


/**
 * 作者:王世富
 * 日期:2021/11/15
 * 说明:会员价管理
 */

@Route(path = PathGoods.VipPriceManageActivity)
public class VipPriceManageActivity extends BaseActivity<VipPriceManageVieModel, ActivityVipPriceManageBinding> {
    @Override
    protected int layoutId() {
        return R.layout.activity_vip_price_manage;
    }

    @Override
    protected void createViewModel() {
        mViewModel = new ViewModelProvider(this).get(VipPriceManageVieModel.class);
        mBinding.setVariable(BR.ViewModel, mViewModel);
    }


    private VipPriceManageListAdpater madpater;
//    private DictWindow4 choice_datatype;
    private StoragePopWindow storagePopWindow;
    private CategoryPopWindow3 categoryPopWindow3;
    private IpPopWindow brandPopWindow;//会员价商品状态

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().removeStickyEvent(this);
    }

    @Override
    protected void init() {
        EventBus.getDefault().register(this);
        initRecyclerView();
        initObserve();
        initClick();
        mViewModel.initDataForType();
        mViewModel.onRefresh();
    }

    private void initClick() {
        mBinding.tvAddnewvipprice.setOnClickListener(this);
        mBinding.backView.setOnClickListener(this);
        mBinding.llChoiceType.setOnClickListener(this);
        mBinding.llChoiceStorage.setOnClickListener(this);
        mBinding.linChoiceClass.setOnClickListener(this);
        mBinding.editView.setOnClickListener(this);
        mBinding.editSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                mViewModel.goods_search = mBinding.editSearch.getText().toString();
            }
        });
    }

    private void initRecyclerView() {
        madpater = new VipPriceManageListAdpater(this);
        mBinding.recyclerview.setLoadingListener(mViewModel);
        mBinding.recyclerview.setLayoutManager(new LinearLayoutManager(this));
        mBinding.recyclerview.setAdapter(madpater);


        madpater.setOnItemClick(new AdapterOnItemClick<VipPriceMangeListEntity>() {
            @Override
            public void onItemClick(VipPriceMangeListEntity vipPriceMangeListEntity, int position) {
                switch (position) {
                    case VipPriceManageListAdpater.COLOSVIPPRICE:
                        DialogHelper.showDialog(VipPriceManageActivity.this, "温馨提示", "结束会员价后商品恢复原价，是否确认结束该商品会员价！", "确定", new DialogFunction() {
                            @Override
                            public void normalRoundDialog() {
                                mViewModel.finishItemMemberPrice(vipPriceMangeListEntity.getId(), vipPriceMangeListEntity.getItemMemberId());
                            }
                        });

                        break;
                    case VipPriceManageListAdpater.SETORICEAGIN:
                        mViewModel.isCanSetingAgin(vipPriceMangeListEntity.getId(), vipPriceMangeListEntity.getItemMemberId());
                        break;
                    default:
                        com.swgk.core.common.utils.ActivityJump.startActivity(PathGoods.MemberPriceDetailsActivity, Pair.create("itemMemberId", vipPriceMangeListEntity.getItemMemberId() + ""), Pair.create("itemId", vipPriceMangeListEntity.getId() + ""));
                        break;
                }
            }
        });

    }


    private void initObserve() {
        mViewModel.listdata.observe(this, listdata -> {
            if (mViewModel.isloadmore) {
                if (null != listdata && listdata.size() > 0) {
                    mBinding.recyclerview.loadMoreComplete();
                    madpater.addDatas(listdata);
                } else {
                    mBinding.recyclerview.setNoMore(true);
                }
                mBinding.recyclerview.setVisibility(View.VISIBLE);
            } else {
                mBinding.recyclerview.refreshComplete();
                if (listdata.size() == 0) {
                    madpater.setDatasMayNull(listdata);
                    mBinding.layoutNull.setVisibility(View.VISIBLE);
                } else {
                    mBinding.layoutNull.setVisibility(View.GONE);
                    mBinding.recyclerview.setVisibility(View.VISIBLE);
                    madpater.setDatas(listdata);
                }
            }
        });

        mViewModel.listdata_Storage.observe(this, lisdata -> {
            if (!storagePopWindow.isShowing()) {
                storagePopWindow.showDownPopwindow(mBinding.grayLayout, true);
            }
            storagePopWindow.setData(lisdata, mViewModel.isIsloadmore_forStorage);
        });

        mViewModel.list_GoodsCategory.observe(this, listdata -> {
            categoryPopWindow3.setDatas(listdata);
        });

        mViewModel.dialog_show_text.observe(this, data -> {
            if (!TextUtils.isEmpty(data)) {
                DialogHelper.showDialog(this, "温馨提示", data, null, "知道了", new DialogFunction() {
                    @Override
                    public void normalRoundDialog() {
                        mViewModel.onRefresh();
                    }
                });
            }
        });
    }

    @Override
    protected void onMultiClick(View v) {
        super.onMultiClick(v);
        switch (v.getId()) {
            case R.id.tv_addnewvipprice:
                com.swgk.core.common.utils.ActivityJump.startActivity(PathGoods.ChoiceVipPriceGoodsActivity);
                break;
            case R.id.back_view:
                finish();
                break;

            case R.id.ll_choice_type://选择会员价商品状态
                showGoodsTypePopWindow();
                break;

            case R.id.ll_choice_storage://选择仓储地址
                showStoragePopWindow();
                break;

            case R.id.lin_choice_class:
                showGoodsClassPopWindow();
                break;
            case R.id.edit_view:
                mViewModel.onRefresh();
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void vipPriceEvent(VipPriceEvent event) {
        if (event == null) {
            return;
        } else {
            mViewModel.onRefresh();
        }
    }

    /**
     * 选择商品状态下拉弹窗
     */
    public void showGoodsTypePopWindow() {

        mBinding.imageType.setImageResource(R.mipmap.icon_up_red);
        mBinding.tvType.setTextColor(getResources().getColor(R.color.color_main));
        if(brandPopWindow==null) {
            brandPopWindow = new IpPopWindow(this);
            brandPopWindow.setOnResultClick((type, key2, key3) -> {

                mBinding.tvType.setText(((IpPickSelectEntity) type).getName());
                mViewModel.itemMemberStatus = ((IpPickSelectEntity) type).getId();
                mViewModel.onRefresh();
                brandPopWindow.dismiss();
            });
            brandPopWindow.setOnDismissListener(() -> {
                if(!TextUtils.isEmpty( mViewModel.itemMemberStatus)){
                    mBinding.tvType.setTextColor(getResources().getColor(R.color.color_main));
                    mBinding.imageType.setImageResource(R.mipmap.icon_down_red);
                }else{
                    mBinding.imageType.setImageResource(R.mipmap.ic_down_arrow_n);
                    mBinding.tvType.setTextColor(getResources().getColor(R.color.color_black_ff666666));
                }
            });
            brandPopWindow.setBgView(mBinding.grayLayout);
            brandPopWindow.setBackground(R.color.white);
            brandPopWindow.setData(mViewModel.choice_type_list);
        }

        brandPopWindow.showPopwindow(mBinding.llChoiceType, 0, 0);



    }

    /**
     * 选择仓储地址
     */
    public void showStoragePopWindow() {
        mBinding.imageStorage.setImageResource(R.mipmap.icon_up_red);
        mBinding.tvStorage.setTextColor(getResources().getColor(R.color.color_main));
        mViewModel.storage = "";
        mViewModel.storageId = "";
        if (storagePopWindow == null) {
            storagePopWindow = new StoragePopWindow(this);
            storagePopWindow.setBgView(mBinding.grayLayout);
            storagePopWindow.setInputMethodMode(PopupWindow.INPUT_METHOD_NEEDED);
            storagePopWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
            storagePopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
                @Override
                public void result(Object key1, Object key2, Object key3) {
                    StorageManEntity storageManEntity = (StorageManEntity) key1;
                    if (storageManEntity == null) {
                        return;
                    }
                    mViewModel.storage = storageManEntity.getStorageName();
                    mViewModel.storageId = storageManEntity.getNo();
                    mViewModel.onRefresh();
                    storagePopWindow.dismiss();
                }
            });
            storagePopWindow.inputTextInterface(new StoragePopWindow.InputTextInterface() {
                @Override
                public void input(String s) {
                    hideInput();
                    mViewModel.search = s;
                    mViewModel.getStorageList(false);
                }
            });
            storagePopWindow.onLodMoreListen(new StoragePopWindow.ILodMore() {
                @Override
                public void onRefresh() {
                    mViewModel.getStorageList(false);
                }

                @Override
                public void onLoadMore() {
                    mViewModel.getStorageList(true);
                }
            });
            storagePopWindow.setOnDisMissClick(new BasePopWindow.OnDisMiss() {
                @Override
                public void disMiss() {
                    if(!TextUtils.isEmpty(mViewModel.storage)&&!TextUtils.isEmpty(mViewModel.storageId)){

                        mBinding.imageStorage.setImageResource(R.mipmap.icon_down_red);
                        mBinding.tvStorage.setTextColor(getResources().getColor(R.color.color_main));
                    }else{
                        mBinding.imageStorage.setImageResource(R.mipmap.ic_down_arrow_n);
                        mBinding.tvStorage.setTextColor(getResources().getColor(R.color.color_black_ff666666));
                    }
                }
            });


        }
        mViewModel.getStorageList(false);
        storagePopWindow.showAddll(false);
        if (!storagePopWindow.isShowing()) {
            storagePopWindow.showDownPopwindow(mBinding.grayLayout, true);
        }


    }

    /**
     * 选择商品分类
     */
    public void showGoodsClassPopWindow() {
        mBinding.imageClass.setImageResource(R.mipmap.icon_up_red);
        mBinding.tvClass.setTextColor(getResources().getColor(R.color.color_main));
        if (categoryPopWindow3 == null) {
            categoryPopWindow3 = new CategoryPopWindow3(this);
            categoryPopWindow3.setOnResultClick(new BasePopWindow.OnResultClick() {
                @Override
                public void result(Object key1, Object key2, Object key3) {
                    mViewModel.cid1 = key1!=null?key1 + "":"";
                    mViewModel.cid3 = key2!=null?key2 + "":"";
                    mViewModel.onRefresh();
                    categoryPopWindow3.dismiss();

                }
            });
            categoryPopWindow3.setOnCloseBack(new DictWindow3.OnCloseBack() {
                @Override
                public void dismiss() {
                    if(TextUtils.isEmpty(mViewModel.cid1)&&TextUtils.isEmpty(mViewModel.cid3)) {
                        mBinding.imageClass.setImageResource(R.mipmap.ic_down_arrow_n);
                        mBinding.tvClass.setTextColor(getResources().getColor(R.color.color_black_ff666666));
                    }else{
                        mBinding.imageClass.setImageResource(R.mipmap.icon_down_red);
                        mBinding.tvClass.setTextColor(getResources().getColor(R.color.color_main));
                    }
                }
            });
            mViewModel.getGoodsCategoryModel();
        }

        categoryPopWindow3.showDownPopwindow(mBinding.grayLayout, true);

    }



    protected void hideInput() {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        View v = getWindow().peekDecorView();
        if (null != v) {
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
    }
}
